package began

import (
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"
	"google.golang.org/grpc/reflection"
	"log"
	"net"
	"os"
	"os/signal"
	"strconv"
	"syscall"
)

func NewGrpcServer(port int, f func(s *grpc.Server)) {
	lis, err := net.Listen("tcp", "0.0.0.0:"+strconv.Itoa(port))
	if err != nil {
		log.Fatal("监听端口"+strconv.Itoa(port)+"失败", err)
		return
	}

	s := grpc.NewServer()
	healthpb.RegisterHealthServer(s, health.NewServer())

	//反射接口
	reflection.Register(s)
	log.Println("grpc服务启动成功...")
	f(s)

	go func() {
		err = s.Serve(lis)
		if err != nil {
			log.Fatal("rpc服务启动失败", err)
			return
		}
	}()

	//优雅关停
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

}
